package org.myspringframework.beans.factory.config;

import org.myspringframework.beans.BeansException;
import org.myspringframework.beans.factory.config.beandefinition.BeanDefinition;

import java.lang.reflect.Method;

//提供了一种通用的适配器模式，使得 Spring 能够处理各种销毁逻辑，无论目标 bean 是否实现了 DisposableBean 接口。
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        // 1. 实现接口 DisposableBean
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2. 配置信息 destroy-method {判断是为了避免二次执行销毁}
        if (destroyMethodName!=null && destroyMethodName!=""&& "destroy".equals(this.destroyMethodName)) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("在"+beanName+"中找不到销毁方法:"+destroyMethodName);
            }
            destroyMethod.invoke(bean);
        }
        
    }

}